<template>
  <div class="welcome-header">
    <!-- 左侧欢迎信息 -->
    <div class="welcome-info">
      <h2>
        <span class="greeting">{{ greetingText }}</span>
        <span class="username">{{ nickName }}</span>
        <span class="welcome-text">，欢迎回来！</span>
      </h2>
      <div class="date-info">
        <i class="el-icon-date"></i>
        <span>{{ currentDate }}</span>
      </div>
    </div>

    <!-- 右侧天气信息 -->
<!--    <div class="weather-info" v-if="weatherData">
      <div class="weather-main">
        <img :src="weatherIcon" class="weather-icon" />
        <span class="weather-temp">{{ weatherData.temp }}℃</span>
      </div>
      <div class="weather-details">
        <span>{{ weatherData.weather }}</span>
        <span>湿度 {{ weatherData.humidity }}%</span>
        <span>{{ weatherData.windDir }} {{ weatherData.windScale }}级</span>
      </div>
    </div>-->
    <!-- 右侧天气信息 -->
    <div class="weather-container" v-if="weatherData">
      <div v-if="weatherLoading" class="weather-loading">
        <i class="el-icon-loading"></i>
        <span>获取天气中...</span>
      </div>

      <div v-else-if="weatherError" class="weather-error">
        <i class="el-icon-warning"></i>
        <span>{{ weatherError }}</span>
      </div>

      <div v-else class="weather-info">
        <div class="weather-main">
          <img :src="weatherIcon" class="weather-icon" alt="天气图标"/>
          <span class="weather-temp">{{ weatherData.temp }}℃</span>
        </div>
        <div class="weather-details">
          <span>{{ weatherData.weather }}</span>
          <span>湿度 {{ weatherData.humidity }}%</span>
          <span>{{ weatherData.wind }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import sunnyIcon from '@/assets/weather/weather-sunny.png'
import cloudyIcon from '@/assets/weather/weather-cloudy.png'
import rainyIcon from '@/assets/weather/weather-rainy.png'
import snowyIcon from '@/assets/weather/weather-snowy.png'
import {mapGetters} from "vuex";

export default {
  name: 'WelcomeHeader',
  data() {
    return {
      userName: '管理员',
      currentDate: new Date(),
      weatherData: null,
      weatherLoading: false,
      weatherError: null,
      weatherIcons: {
        '晴': sunnyIcon,
        '多云': cloudyIcon,
        '阴': cloudyIcon,
        '雨': rainyIcon,
        '雪': snowyIcon
      },
      dateUpdateInterval: null,
      // 和风天气的API key，请替换成你自己的
      weatherApiKey: 'Q003EAAB3A',
      timer: null
    }
  },

  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'device',
      'nickName'
    ]),
    // 根据时间生成问候语
    greetingText() {
      const hour = new Date().getHours()
      if (hour < 6) return '凌晨好'
      if (hour < 9) return '早上好'
      if (hour < 12) return '上午好'
      if (hour < 14) return '中午好'
      if (hour < 18) return '下午好'
      return '晚上好'
    },
    // 天气图标
    weatherIcon() {
      return this.weatherIcons[this.weatherData?.weather] || sunnyIcon
    }
  },
  created() {
    this.updateDate()
    this.fetchWeather()
    // 每分钟更新一次时间,改成10秒执行一次
    this.timer = setInterval(this.updateDate, 10000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    // 更新当前日期时间
    updateDate() {
      const now = new Date()
      const options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long',
        hour: '2-digit',
        minute: '2-digit'
      }
      this.currentDate = now.toLocaleDateString('zh-CN', options)
    },
    // 获取天气数据
    async fetchWeather() {
      this.weatherLoading = true
      this.weatherError = null

      try {
        // 1. 尝试从缓存获取
        const cachedWeather = this.getCachedWeather()
        if (cachedWeather) {
          this.weatherData = cachedWeather
          return
        }

        // 2. 获取地理位置
        const position = await this.getUserPosition()
        // 3. 调用天气API
        const params = {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude
        }
        /*const res = await getWeatherByLocation(params)
        // 4. 处理返回数据
        this.weatherData = {
          temp: res.data.temp,
          weather: res.data.weather,
          humidity: res.data.humidity,
          wind: `${res.data.windDir} ${res.data.windScale}级`,
          city: res.data.city || '当前位置'
        }

        // 5. 缓存天气数据（有效期2小时）
        this.cacheWeather(this.weatherData)
        */
      } catch (error) {
        console.error('获取天气失败:', error)
        this.weatherError = this.getErrorMessage(error)
        // 显示默认数据
        this.weatherData = null
        // this.weatherData = {
        //   temp: '--',
        //   weather: '未知',
        //   humidity: '--',
        //   wind: '--',
        //   city: '未知位置'
        // }
      } finally {
        this.weatherLoading = false
      }
    },

    // 获取用户地理位置
    getUserPosition() {
      return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
          reject(new Error('浏览器不支持地理位置服务'))
        }

        navigator.geolocation.getCurrentPosition(
          position => resolve(position),
          error => {
            // 根据错误码返回友好提示
            const errorMap = {
              1: '用户拒绝了位置请求',
              2: '无法获取您的位置',
              3: '请求位置超时'
            }
            reject(new Error(errorMap[error.code] || '位置获取失败'))
          },
          {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 300000
          }
        )
      })
    },

    // 从缓存获取天气
    getCachedWeather() {
      const cache = localStorage.getItem('weatherCache')
      if (!cache) return null

      const { timestamp, data } = JSON.parse(cache)
      // 缓存有效期2小时
      if (Date.now() - timestamp < 7200000) {
        return data
      }
      return null
    },

    // 缓存天气数据
    cacheWeather(data) {
      localStorage.setItem('weatherCache', JSON.stringify({
        timestamp: Date.now(),
        data
      }))
    },

    // 错误信息处理
    getErrorMessage(error) {
      if (error.message.includes('用户拒绝了')) {
        return '已拒绝位置权限，将显示默认天气'
      }
      if (error.message.includes('无法获取')) {
        return '无法获取您的位置，请检查网络'
      }
      return '天气服务暂不可用'
    },

    // 获取天气数据,暂时不用
    async getWeather() {
      if (!this.location.trim()) {
        this.error = '请输入城市名称';
        return;
      }

      this.loading = true;
      this.error = null;
      this.weatherData = null;

      try {
        // 使用和风天气API
        const response = await this.$http.get(
          `https://devapi.qweather.com/v7/weather/now?location=${encodeURIComponent(this.location)}&key=${this.weatherApiKey}`
        );

        if (response.data.code === '200') {
          // 获取当前天气
          const nowData = response.data;

          // 获取3天预报
          const forecastResponse = await this.$http.get(
            `https://devapi.qweather.com/v7/weather/3d?location=${encodeURIComponent(this.location)}&key=${this.weatherApiKey}`
          );

          if (forecastResponse.data.code === '200') {
            this.weatherData = {
              basic: {
                city: nowData.location.name
              },
              now: {
                temp: nowData.now.temp,
                cond_txt: nowData.now.text,
                hum: nowData.now.humidity,
                wind_spd: nowData.now.windSpeed
              },
              daily_forecast: forecastResponse.data.daily.map(day => ({
                date: day.fxDate,
                tmp_max: day.tempMax,
                tmp_min: day.tempMin,
                cond_txt_d: day.textDay
              }))
            };
          } else {
            this.error = forecastResponse.data.message || '获取预报数据失败';
          }
        } else {
          this.error = response.data.message || '获取天气数据失败';
        }
      } catch (err) {
        console.error('获取天气出错:', err);
        this.error = '获取天气信息失败，请稍后再试';
      } finally {
        this.loading = false;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.welcome-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 25px;
  background: linear-gradient(135deg, #1976D2, #2196F3);
  color: white;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .welcome-info {
    h2 {
      margin: 0 0 5px 0;
      font-size: 20px;
      font-weight: normal;

      .username {
        font-weight: bold;
        margin: 0 5px;
      }
    }

    .date-info {
      display: flex;
      align-items: center;
      font-size: 14px;
      opacity: 0.9;

      i {
        margin-right: 6px;
        font-size: 16px;
      }
    }
  }

  .weather-info {
    display: flex;
    align-items: center;

    .weather-main {
      display: flex;
      align-items: center;
      margin-right: 15px;

      .weather-icon {
        width: 40px;
        height: 40px;
        margin-right: 8px;
      }

      .weather-temp {
        font-size: 24px;
        font-weight: bold;
      }
    }

    .weather-details {
      display: flex;
      flex-direction: column;
      font-size: 13px;
      line-height: 1.5;
      border-left: 1px solid rgba(255, 255, 255, 0.3);
      padding-left: 15px;
    }
  }
}

@media (max-width: 768px) {
  .welcome-header {
    flex-direction: column;
    text-align: center;
    padding: 15px;

    .weather-info {
      margin-top: 15px;
      flex-direction: column;

      .weather-main {
        margin-right: 0;
        margin-bottom: 8px;
      }

      .weather-details {
        border-left: none;
        padding-left: 0;
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: center;

        span {
          margin: 0 8px;
        }
      }
    }
  }
}
@media (prefers-color-scheme: dark) {
  .welcome-header {
    background: linear-gradient(135deg, #0d47a1, #1976d2);
  }
}
.weather-icon {
  transition: transform 0.3s;
  &:hover {
    transform: scale(1.1);
  }
}
h2 {
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}
</style>
